package com.hhf.feiojcommonservice.utils;

import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @Author hhf
 * @Date 2024/11/6
 * @Description JWT 封装工具包
 */
@Slf4j
public class JwtUtils {

    /**
     * 7天过期
     */
    public static final long TOKEN_EXPIRE_MILLIS = 1000 * 60 * 60 * 24 * 7L;

    /**
     * key（按照签名算法的字节长度设置key）
     */
    private static final String SECRET_KEY = "0123456789_0123456789_0123456789";


    /**
     * 生成Token
     *
     * @param object
     * @return
     */
    public static String genToken(Object object) {

        long currentTimeMillis = System.currentTimeMillis();

        return Jwts.builder()
                .claim("userId",object)
                .id(UUID.randomUUID().toString())
                .issuedAt(new Date(currentTimeMillis))                              //签发时间
                .expiration(new Date(currentTimeMillis + TOKEN_EXPIRE_MILLIS))      //过期时间
                .signWith(genKey())
                .compact();
    }

    /**
     * 解析Token
     *
     * @return
     */
    public static Object parseToken(String token) {

        try {
            return Jwts.parser()
                    .verifyWith(genKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload()
                    .get("userId");
        } catch (JwtException e) {
            log.error("JWT token parse error:{}",e.getMessage());
            return null;
        }
    }


    public static SecretKey genKey() {
        return new SecretKeySpec(SECRET_KEY.getBytes(), SignatureAlgorithm.HS256.getJcaName());
    }

}
